const express = require('express');
const axios = require('axios');
const ejs = require('ejs');
const path = require('path');
const fs = require('fs');
const puppeteer = require('puppeteer');
const AdmZip = require('adm-zip');
const uuid = require('uuid');
const { config } = require('../../config');
const SqliteDB = require('../../config/sqlite');
const dayjs = require('dayjs');
const {createLogInfo} = require('../../config/logConfig');
const { reportData} = require('../../report-t');

const db = new SqliteDB();
const operatorRouter = express.Router();
const reportBaseUrl = {
    reportViewPage: 'course-server/course/classroom/report4/score/reportViewPage',
};

operatorRouter.post('/getPdfZip', async (req, res) => {
    axios.post(`${config.baseUrl}${reportBaseUrl.reportViewPage}`, req.body, {
        headers: {
            Authorization: req.get('Authorization')
        }
    }).then(async result => {
        try {
            let logStr = `
地址：${req.url}
请求方式：${req.method}
参数：${JSON.stringify(req.body)}
时间：${dayjs().format('YYYY-MM-DD HH:mm:ss.SSS')}
响应数据长度：${result.data.datas.length}
            `;
            if (result.data.datas && result.data.datas.length) {
                let str = logStr += `响应数据长度：${result.data.datas.length}`;
                createLogInfo(str);
                const row = result.data.datas[0].report4;
                const id = uuid.v4();
                db.insertData('zip_progress', {
                    id,
                    class_name: row.className,
                    course_name: row.courseName,
                    progress: `0 / ${result.data.datas.length}`,
                    created_at: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                    updated_at: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
                });
                const bufferList = await printAll(result.data.datas, id);
                const zipList = generatorZip(bufferList, result.data.datas);
                db.updateData('zip_progress', {
                    progress: `${result.data.datas.length} / ${result.data.datas.length}`
                }, `id = '${id}'`)
                // 将zip写入本地
                const localPath = path.join(__dirname, `../../pdfZip/${dayjs(new Date()).format('YYYY-MM-DD')}`);
                if (!fs.existsSync(localPath)) {
                    fs.mkdirSync(localPath);
                }
                fs.writeFileSync(path.join(__dirname, `../../pdfZip/${dayjs(new Date()).format('YYYY-MM-DD')}/${id}.zip`), zipList);
                const courseName = result.data.datas[0].report4.courseName;
                const className = result.data.datas[0].report4.className;
                const reportName = encodeURI(courseName + ' ' + className);
                res.setHeader('Content-Type', 'application/zip');
                res.setHeader('Content-Disposition', 'attachment; filename=' + reportName + '.zip');
                res.status(200);
                res.send(zipList);
            } else {
                createLogInfo(logStr);
                res.json(result.data);
            }
        } catch (e) {
            console.log('getPdfZip接口出错');
            console.log(e);
        }
    });
});

operatorRouter.post('/downloadPdf', async (req, res) => {
    axios.post(`${config.baseUrl}${reportBaseUrl.reportViewPage}`, req.body, {
        headers: {
            Authorization: req.get('Authorization')
        }
    }).then(async result => {
        try {
            if (result.data.datas && result.data.datas.length) {
                const replaceData = replaceTeacherName(result.data.datas[0]);
                const pdfStream = await resPdfStream(replaceData);
                res.set('Content-Type', 'application/pdf');
                const fileName = encodeURI(result.data.datas[0].name + '-' + result.data.datas[0].number);
                res.setHeader('Content-Disposition', 'attachment; filename=' + fileName + '.pdf');
                res.status(200);
                res.send(pdfStream);
            } else {
                res.json(result.data);
            }
        } catch (e) {
            console.log('/downloadPdf接口出错');
            console.log(e);
        }
    });
});

operatorRouter.get('/preview', async (req, res) => {
    const pdfStream = await resPdfStream(reportData);
    res.set('Content-Type', 'application/pdf');
    res.send(pdfStream);
});

async function getEjsHtml(data) {
    return await new Promise((resolve, reject) => {
        ejs.renderFile(path.resolve(__dirname, '../../views/index.ejs'), data, function (err, str) {
            if (err) {
                reject(err);
            } else {
                resolve(str);
            }
        });
    });
}

async function printPDF(page, index, dataMap, total, dataId) {
    const html = await getEjsHtml(dataMap);
    const startTime = new Date().getTime();
    console.log(`第${index + 1}份开始生成...`);
    await page.setContent(html);
    const result = await page.pdf({
        format: 'A4',
        printBackground: true,
        displayHeaderFooter: true,
        headerTemplate: `<div style="width: 100%; text-align: center; font-size: 10px;color: transparent">
                                <span class="date">${new Date().toLocaleDateString()}</span>
                            </div>`,
        footerTemplate: `<div style="width: 100%; text-align: center; font-size: 10px;">
                                <span class="pageNumber"></span> / <span class="totalPages"></span>
                            </div>`,
        margin: {
            top: '1cm',
            bottom: '1cm',
            left: '1cm',
            right: '1cm'
        },
    });
    console.log(`第${index + 1}份生成成功，耗时：${new Date().getTime() - startTime}ms`);
    db.updateData('zip_progress', {
        progress: `${index + 1} / ${total}`
    }, `id = '${dataId}'`);
    return result;
}

async function printAll(dataList, dataId) {
    const pdfBufferList = [];
    const browser = await puppeteer.launch({
        headless: true,
        // executablePath: 'xxxxx.chrome.exe', // 谷歌浏览器的绝对路径
        args: ['--no-sandbox']
    });
    const page = await browser.newPage();
    console.log(`共${dataList.length}份`);
    for (let i = 0; i < dataList.length; i++) {
        const replaceData = replaceTeacherName(dataList[i]);
        pdfBufferList.push(await printPDF(page, i, replaceData, dataList.length, dataId));
    }
    console.log('完成，关闭浏览器');
    await browser.close();
    return pdfBufferList;
}


function generatorZip(bufferList, dataList) {
    const zip = new AdmZip();
    bufferList.map((item, index) => {
        zip.addFile(`${dataList[index].name}-${dataList[index].number}.pdf`, item);
    });
    return zip.toBuffer();
}

async function resPdfStream(data) {
    const browser = await puppeteer.launch({
        headless: true,
        // executablePath: 'xxxxx.chrome.exe', // 谷歌浏览器的绝对路径
        args: ['--no-sandbox']
    });
    const page = await browser.newPage();
    const html = await getEjsHtml(data);
    await page.setContent(html);
    const result = await page.pdf({
        format: 'A4',
        printBackground: true,
        displayHeaderFooter: true,
        headerTemplate: `<div style="width: 100%; text-align: center; font-size: 10px;color: transparent">
                                <span class="date"></span>
                            </div>`,
        footerTemplate: `<div style="width: 100%; text-align: center; font-size: 10px;">
                                <span class="pageNumber"></span> / <span class="totalPages"></span>
                            </div>`,
        margin: {
            top: '1cm',
            bottom: '1cm',
            left: '1cm',
            right: '1cm'
        },
    });
    await browser.close();
    return result;
}

const replaceTeacherName = (data) => {
    if (config.replaceSemesterInfo.semesterId === data.report4.semesterId) {
        if (data.teacherName === config.replaceSemesterInfo.source) {
            data.teacherName = config.replaceSemesterInfo.target
        }
    }
    return data;
}

module.exports = operatorRouter;
